package com.example.base.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.base.entity.User;

import java.util.HashMap;
import java.util.Map;

public class TokenUtils {
    private static final String MY_SECRET = "mysecret";

    public static String getToken(User user) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        return JWT.create().withHeader(map)// header
                .withClaim("email", user.getEmail())// payload
                .sign(Algorithm.HMAC256(MY_SECRET));
    }

    public static void verifyToken(String token) throws JWTVerificationException {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(MY_SECRET)).build();
        verifier.verify(token);
    }

    public static void main(String[] args) {
        User user = new User();
        user.setEmail("123456@qq.com");
        String str = getToken(user);
        System.out.println(str);
        try {
            verifyToken(str);
        } catch (JWTVerificationException e) {
            System.out.println("验证失败");
        }
    }
}
